import axios from "axios";
import type { AxiosInstance } from "axios";
import { ElLoading } from "element-plus";

import type { ZYRequestInterceptors, ZYRequestConfig } from "./type";

const SHOW_LOADING = true;

class ZYRequest {
  instance: AxiosInstance;
  interceptors?: ZYRequestInterceptors;
  load: any;
  showLoading: boolean;
  // config: ZYRequestConfig;

  constructor(config: ZYRequestConfig) {
    // this.config = config;
    this.instance = axios.create(config);
    this.interceptors = config.interceptors;
    this.showLoading = SHOW_LOADING;

    //实例特有的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );

    //添加所有的实例都有的--请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.load = ElLoading.service({
            lock: true,
            text: "正在加载...",
            background: "rgba(0, 0, 0, 0.7)",
          });
        }
        return config;
      },
      (config) => {
        return config;
      }
    );

    //添加所有的实例都有的--响应拦截器
    this.instance.interceptors.response.use(
      (config) => {
        this.load?.close();
        return config.data;
      },
      (config) => {
        this.load?.close();
        return config;
      }
    );
  }

  request<T>(config: ZYRequestConfig<T>): Promise<T> {
    if (config.showLoading === false) {
      this.showLoading = false;
    }
    //添加单独的请求拦截和响应拦截
    if (config.interceptors?.requestInterceptor) {
      config = config.interceptors.requestInterceptor(config); //通过调用传进来的对象来实现
    }

    return new Promise((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res);
          }

          resolve(res);
        })
        .catch((err) => {
          reject(err);
        })
        .finally(() => {
          this.showLoading = SHOW_LOADING;
        });
    });
  }

  get<T>(config: ZYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "GET" });
  }
  post<T>(config: ZYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "POST" });
  }
  delete<T>(config: ZYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "DELETE" });
  }
  patch<T>(config: ZYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "PATCH" });
  }
}

export default ZYRequest;
